/****************
 *@description: 宠币商品管理   myPocket/petCoins/index
 *@author: Xhd
 *@API: 方子奥
 *@date: 2023-11-27 11:06:43
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import { Form, InputNumber, Modal, Space, Divider, Input, Tabs } from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import {
  apiImPetCoinsList, apiImPetCoinsAdd, apiImPetCoinsUpdate, apiImPetCoinsDelete, apiImPetCoinsUpOrDownShelves,
  apiImCustomCoinsGet, apiImCustomCoinsUpdate
} from "@/request/petCoins";

const { TabPane } = Tabs;
class PetCoins extends Component {
  constructor(props) {
    super(props)
    this.upDateFromRef = React.createRef()
    this.petCoinsCustRef = React.createRef()
    this.state = {
      columns: [
        {
          title: "宠币ID",
          dataIndex: "imPetCoinsId",
          key: "imPetCoinsId"
        },
        {
          title: "宠币数额",
          dataIndex: "coinsAmount",
          key: "coinsAmount",
          render: (text) => {
            return text / 10 + "币"
          }
        },
        {
          title: "购买价格",
          dataIndex: "coinUnitPrice",
          key: "coinUnitPrice",
          render: text => text / 100,
        },
        {
          title: "排序",
          dataIndex: "sort",
          key: "sort",
          sorter: true,
          sortDirections: ["ascend", "descend"]
        },
        {
          title: "宠币状态",
          dataIndex: "coinStatus",
          key: "coinStatus",
          render: (text, record) => {
            let tet = ""
            switch (text) {
              case 0:
                tet = "下架"
                break;
              case 1:
                tet = "上架"
                break;
              default:
                break;
            }
            return tet;
          }
        },
        {
          title: "上传时间",
          dataIndex: "createTime",
          key: "createTime"
        },
        {
          title: "操作",
          fixed: "right",
          width: 300,
          render: (text, record) => {
            return (
              <div>
                <TheButton
                  haspermi={["myPocket:petCoins:edit"]}
                  onClick={() => this.goDetail(record, "update")}
                >
                  编辑
                </TheButton>
                <TheButton
                  haspermi={["myPocket:petCoins:deleted"]}
                  onClick={() => this.deletedCoins(record.imPetCoinsId)}
                >
                  删除
                </TheButton>
                {(record.coinStatus === 0) && (
                  <TheButton
                    haspermi={["myPocket:petCoins:putShelf"]}
                    onClick={() => this.putShelf(record.imPetCoinsId, 1)}
                  >
                    上架
                  </TheButton>
                )}
                {record.coinStatus === 1 && (
                  <TheButton
                    haspermi={["myPocket:petCoins:putShelf"]}
                    onClick={() => this.putShelf(record.imPetCoinsId, 0)}
                  >
                    下架
                  </TheButton>
                )}
              </div>
            );
          },
        },
      ],
      dataSource: [],
      initialValues: {},
      petCoinsUpdate: false,
      petCoinsCust: false,
      petType: "add",
      petCoinsCustInitialValues: {},
      type: 0,
      iosOrAndroid: 0,
    }
  }

  componentDidMount() {
    this.getData()
    this.getPetCoinsCust()
  }

  getData = async () => {
    const { type, iosOrAndroid } = this.state
    let res = await apiImPetCoinsList({ iosOrAndroid, type })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data
      })
    }
  }

  getPetCoinsCust = async () => {
    const { iosOrAndroid } = this.state
    let type = iosOrAndroid == 0 ? 0 : 1
    let res = await apiImCustomCoinsGet({ type })
    if (res.code === 0 && res.data) {
      let data = res.data
      data.minimumRechargeAmount = data.minimumRechargeAmount ? data.minimumRechargeAmount / 100 : ""
      data.maxmumRechargeAmount = data.maxmumRechargeAmount ? data.maxmumRechargeAmount / 100 : ""
      this.setState({
        petCoinsCustInitialValues: data
      })
    }
  }

  putShelf = async (imPetCoinsId, coinStatus) => {
    let res = await apiImPetCoinsUpOrDownShelves({ imPetCoinsId, coinStatus })
    if (res.code === 0 && res.data) {
      React.$message({
        type: "success",
        content: coinStatus === 0 ? "下架成功" : "上架成功"
      })
      this.getData()
    }
  }

  deletedCoins = (imPetCoinsId) => {
    React.$confirm({
      title: "删除确认",
      content: "确认删除该宠币商品吗",
      onOk: async () => {
        let res = await apiImPetCoinsDelete({ imPetCoinsId, deleted: 1 })
        if (res.code === 0 && res.data) {
          React.$message({
            type: "success",
            content: "删除成功"
          })
          this.getData()
        }
      }
    })
  }

  goDetail = (value, type) => {
    value.coinUnitPrice = value.coinUnitPrice / 100
    value.coinsAmount = value.coinsAmount / 10
    this.setState({
      petType: type,
      upDateTitle: "编辑宠币商品",
      initialValues: value,
      petCoinsUpdate: true
    }, () => {
      // console.log(this.upDateFromRef);
      // this.upDateFromRef.setFieldsValue(value)
    })
  }

  onFinish = async (values, type) => {
    const { iosOrAndroid } = this.state
    const { imPetCoinsId } = this.state.initialValues
    values.coinUnitPrice = values.coinUnitPrice * 100
    values.coinsAmount = values.coinsAmount * 10
    values.iosOrAndroid = iosOrAndroid
    if (type === "add") {
      let res = await apiImPetCoinsAdd(values)
      if (res.code === 0) {
        React.$message({
          type: "success",
          content: "上传成功"
        })
        this.setState({ petCoinsUpdate: false })
        this.getData()
      }
    } else {
      let res = await apiImPetCoinsUpdate({ imPetCoinsId, ...values })
      if (res.code === 0) {
        React.$message({
          type: "success",
          content: "上传成功"
        })
        this.setState({ petCoinsUpdate: false })
        this.getData()
      }
    }
  }

  petCoinsCustFinish = async (values) => {
    const { iosOrAndroid } = this.state
    const { imCustomCoinsId } = this.state.petCoinsCustInitialValues
    values.minimumRechargeAmount = values.minimumRechargeAmount * 100
    values.maxmumRechargeAmount = values.maxmumRechargeAmount * 100
    values.iosOrAndroid = iosOrAndroid
    let res = await apiImCustomCoinsUpdate({ imCustomCoinsId, ...values, type: 0 })  // type 0-充值  1-兑换
    if (res.code === 0 && res.data) {
      React.$message({
        type: "success",
        content: "修改成功"
      })
      this.setState({ petCoinsCust: false }, () => {
        this.getPetCoinsCust()
      })
    } else {

    }
  }

  handleTableChange = (pagination, filters, sorter) => {
    let type = 0
    switch (sorter.order) {
      case "ascend":
        type = 1
        break;
      case "descend":
        type = 2
        break;
      default:
        break;
    }
    this.setState({
      type
    }, () => {
      this.getData()
    })
  }

  onChange = (e) => {
    this.setState({
      iosOrAndroid: e
    }, () => {
      this.getData()
      this.getPetCoinsCust()
    })
  }

  render() {
    const { columns, dataSource, initialValues, petCoinsUpdate, petCoinsCust, upDateTitle, petType, petCoinsCustInitialValues, iosOrAndroid } = this.state
    return (<div className="p-layout-box">
      <Tabs defaultActiveKey={iosOrAndroid} onChange={this.onChange} type="card" >
        <TabPane tab="宠币充值" key="0">
          <div style={{ textAlign: "right", padding: "10px" }}>
            <Space>
              <TheButton type="primary" size="middle" haspermi={["myPocket:petCoins:cust"]} onClick={() => { this.setState({ petCoinsCust: true }, () => { this.getPetCoinsCust() }) }} >自定义宠币充值</TheButton>
              <TheButton type="primary" size="middle" haspermi={["myPocket:petCoins:upDate"]} onClick={() => this.setState({ petCoinsUpdate: true, upDateTitle: "请上传宠币商品", initialValues: {}, petType: "add" })} >上传宠币商品</TheButton>
            </Space>
          </div>
          <div>
            注：这里的宠币只对安卓和H5充值有效，苹果宠币购买设置需要在苹果后台设置
          </div>
          <TheTable
            columns={columns}
            dataSource={dataSource}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content', y: '63vh' }}
          />
        </TabPane>
        <TabPane tab="宠币兑换" key="2">
          <div style={{ textAlign: "right", padding: "10px" }}>
            <Space>
              <TheButton type="primary" size="middle" haspermi={["myPocket:petCoins:cust"]} onClick={() => { this.setState({ petCoinsCust: true }, () => { this.getPetCoinsCust() }) }} >自定义宠币兑换</TheButton>
              <TheButton type="primary" size="middle" haspermi={["myPocket:petCoins:upDate"]} onClick={() => this.setState({ petCoinsUpdate: true, upDateTitle: "请上传宠币商品（兑换）", initialValues: {}, petType: "add" })} >上传宠币商品（兑换）</TheButton>
            </Space>
          </div>
          <div>
            注：列表为充币商品和对应兑换金额（礼物收益兑换1:1兑换）
          </div>
          <TheTable
            columns={columns}
            dataSource={dataSource}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content', y: '63vh' }}
          />
        </TabPane>
      </Tabs>

      <Modal visible={petCoinsUpdate} title={upDateTitle} footer={false} destroyOnClose onCancel={() => this.setState({ petCoinsUpdate: false })} >
        <Form ref={(ref) => { this.upDateFromRef = ref }} onFinish={(value) => this.onFinish(value, petType)} initialValues={initialValues}
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 12,
          }} >
          <Form.Item label={iosOrAndroid == 0 ?"购买价格": "兑换价格"} name={"coinUnitPrice"} rules={[{ required: true }]} >
            <InputNumber addonAfter="元" placeholder="请设置购买单价"  min={1} precision={0} maxLength={5}
              onChange={(value) => { this.upDateFromRef.setFieldsValue({ coinsAmount: value * 10 }) }} />
          </Form.Item>
          <Form.Item label="宠币数额" name={"coinsAmount"} rules={[{ required: true }]} >
            <Input disabled placeholder="输入价格后自动计算" addonAfter="宠币" />
          </Form.Item>
          <Form.Item label="排序" name={"sort"} rules={[{ required: true }]} >
            <InputNumber placeholder="数字越小，在APP展示越靠前" min={1} maxLength={3} precision={0} />
          </Form.Item>
          <Divider />
          <div style={{ textAlign: "center" }}>
            <Space>
              <TheButton type="default" size="middle" onClick={() => this.setState({ petCoinsUpdate: false })}>取消</TheButton>
              <TheButton type="primary" size="middle" htmlType="submit" >提交</TheButton>
            </Space>
          </div>
        </Form>
      </Modal>
      <Modal visible={petCoinsCust} title={iosOrAndroid == 0 ? "自定义充值金额设置": "自定义兑换金额设置"} footer={false} onCancel={() => this.setState({ petCoinsCust: false })} destroyOnClose >
        <Form ref={(ref) => this.petCoinsCustRef = ref} initialValues={petCoinsCustInitialValues} onFinish={(values) => this.petCoinsCustFinish(values)} >
          <Form.Item label={iosOrAndroid == 0 ?"最小充值金额": "最小兑换金额"} name={"minimumRechargeAmount"} rules={[{ required: true }]}>
            <InputNumber addonAfter="元" placeholder="请输入最小充值金额"  min={1} maxLength={5} precision={0} />
          </Form.Item>
          <Form.Item label={iosOrAndroid == 0 ?"最大充值金额": "最大兑换金额"} name={"maxmumRechargeAmount"} rules={[{ required: true }]}>
            <InputNumber addonAfter="元" placeholder="请输入最大充值金额"  min={1} maxLength={5} precision={0} />
          </Form.Item>
          <Divider />
          <div style={{ textAlign: "center" }}>
            <Space>
              <TheButton type="default" size="middle" onClick={() => this.setState({ petCoinsCust: false })}>取消</TheButton>
              <TheButton type="primary" size="middle" htmlType="submit" >确定</TheButton>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>)
  }
}

export default PetCoins